<template>
  <a-card :bordered="false">
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-select v-model="queryParam.status" autoClearSearchValue show-search allowClear placeholder="请选择" style="min-width: 200px; margin-right: 24px" @change="handleTenantChange">
        <a-select-option value="0">开启</a-select-option>
        <a-select-option value="1">禁用</a-select-option>
      </a-select> -->

      <a-button @click="handleAdd" type="primary">新增分类</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        @change="handleTableChange"
        @expand="handleExpand"
        :expandedRowKeys="expandedRowKeys"
      >
        <span slot="isMuilt" slot-scope="text, record">
          <span v-if="record.isMuilt != null">
            {{ text | isMuilt }}
          </span>
        </span>
        <span slot="status" slot-scope="text, record, index">
          <a-switch checked-children="开" un-checked-children="关" :checked="record.status == 0" default-checked @change="choose(record, $event ? ischoose : noChoose)" />
        </span>
        <span slot="icon" slot-scope="text, record, index">
          <img :src="record.icon" style="width: 50px; height: 50px" v-if="record.icon" />
          <span v-else></span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" v-has="'tag:edit'" />

          <a @click="sortSub(record)">修改排序</a>
          <a-divider type="vertical" />
          <a @click="handleAddSub(record)">新增子分类</a>
        </span>
      </a-table>
    </div>
    <sysCategory-modal ref="modalForm" @ok="modalFormOk" :tagsType="tagsType"></sysCategory-modal>
    <a-modal v-model="visible" :title="titleName" @ok="handleOk" @cancel="handleCancel" :width="400">
      <div style="display: flex; align-items: center">
        <span>排序调整为：</span>
        <a-input-number v-model="sorted" :min="1" :precision="0" :max="maxNumber" style="width: 200px" />
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import SysCategoryModal from './model/SysCategoryModal'
import { deleteAction } from '@/api/manage'
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'

import { queryItemCateById } from '@/api/goods'
// import LetterModel from './model/letterModel'

export default {
  mixins: [JeecgListMixin],
  components: {
    SysCategoryModal,
    initDictOptions,
    filterDictText

    // LetterModel
  },
  data() {
    return {
      titleName: '',
      sord: '',
      queryParam: {},
      tagsType: '',
      sorted: '',
      description: '标签管理页面',
      maxNumber: null, //排序最大限制
      // 表头
      columns: [
        {
          title: '分类名称',
          align: 'left',
          dataIndex: 'name'
        },
        {
          title: '备注',
          align: 'left',
          dataIndex: 'remark'
        },

        {
          title: '排序',
          align: 'left',
          dataIndex: 'sorted'
        },
        {
          title: '状态',
          align: 'left',
          scopedSlots: { customRender: 'status' }
        },

        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      code: 'B10-A02',
      ischoose: 0,
      noChoose: 1,
      url: {
        list: '/sys/category/rootList',
        childList: '/sys/category/childList',
        getChildListBatch: '/sys/category/getChildListBatch',
        delete: '/sys/category/delete',
        deleteBatch: '/sys/category/deleteBatch',
        exportXlsUrl: '/sys/category/exportXls',
        importExcelUrl: 'sys/category/importExcel'
      },
      expandedRowKeys: [],
      defaultExpandedRowKeys: [],
      hasChildrenField: 'hasChild',
      pidField: 'pid',
      dictOptions: {},
      subExpandedKeys: [],
      disableMixinCreated: true,
      visible: false,
      id: '',
      copyHasChild: '',
      copyPid: '',
      resultChildren: [],
      sortMap: null,
      listArray: [],
      parentId: ''
    }
  },
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: selectedRowKeys => (_this.selectedRowKeys = selectedRowKeys)
        }
      }
    },
    secondRoot() {
      return record => {
        if (record.pid == this.tagsType) {
          return true
        }
      }
    }
  },
  filters: {
    isMuilt(value) {
      if (value == 0) {
        return '否'
      } else if (value == 1) {
        return '是'
      } else {
        return ''
      }
    }
  },
  created() {
    this.fetchPath()
    this.initDictConfig()
    this.parentId = process.env.NODE_ENV === 'production' ? '1560088629817421826' : '1556824470800109570'
  },
  watch: {
    $route(to) {
      this.fetchPath()
    }
  },
  methods: {
    handleTenantChange() {
      this.loadData()
    },
    choose(record, status) {
      let httpurl = '/sys/category/edit'
      let method = 'put'
      let data = {
        status: status,
        id: record.id,
        pid: record.hasChild ? this.parentId : record.pid
      }
      httpAction(httpurl, data, method)
        .then(res => {
          if (res.code == 200) {
            this.$message.success(res.message)
            record.status = status
            this.dataSource = [...this.dataSource]
            this.editOk(record, this.dataSource)
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    showModal() {
      this.visible = true
    },
    handleCancel() {
      this.sorted = ''
      this.visible = false
    },
    // 修改排序
    handleOk() {
      this.sortMap.delete(this.record.sorted)
      const rowProm = httpAction(
        '/sys/category/edit',
        {
          sorted: this.sorted,
          id: this.id,
          pid: this.copyHasChild ? this.parentId : this.copyPid
        },
        'put'
      ).then(res => {})
      const proms = [rowProm]
      let targetSort = this.sorted
      while (this.sortMap.has(targetSort)) {
        const editItem = this.sortMap.get(targetSort)
        this.sortMap.delete(targetSort)
        targetSort = editItem.sorted + 1
        let info = {
          sorted: targetSort,
          id: editItem.id,
          pid: editItem.hasChild ? this.parentId : editItem.pid
        }
        const editProm = httpAction('/sys/category/edit', info, 'put').then(res => {})
        this.editOk(editItem, this.dataSource)
        proms.push(editProm)
        Promise.all(proms).then(() => {
          this.loadData()
          this.expandedRowKeys = []
        })
      }
      this.loadData()
      this.expandedRowKeys = []
      // return

      // let httpurl = '/sys/category/edit'
      // let method = 'put'
      // let data = {
      //   sorted: this.sorted,
      //   id: this.id,
      //   pid: this.copyHasChild ? '1556824470800109570' : this.copyPid
      // }

      // httpAction(httpurl, data, method)
      //   .then(res => {
      //     if (res.code == 200) {
      //       this.record.sorted = this.sorted
      //       this.dataSource = [...this.dataSource]
      //       this.editOk(this.record, this.dataSource)
      //       this.$message.success(res.message)
      //     } else {
      //       this.$message.warning(res.message)
      //     }
      //   })
      //   .finally(() => {
      //     this.confirmLoading = false
      //   })
      this.visible = false
    },

    fetchPath() {
      const arr = this.$route.name.split('-')
      this.tagsType = arr[4]
      this.loadData()
    },
    loadData(arg) {
      if (arg == 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let params = this.getQueryParams()
      console.log(params)
      return new Promise(resolve => {
        getAction(this.url.list, params)
          .then(res => {
            if (res.success) {
              let result = res.result
              if (Number(result.total) > 0) {
                this.ipagination.total = Number(result.total)
                const dataS = this.getDataByResult(res.result.records)
                const dataF = dataS.filter(item => item.id == this.tagsType)
                return this.loadDataBySecond(dataF[0].id)
              } else {
                this.ipagination.total = 0
                this.dataSource = []
              }
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    getDataByResult(result) {
      if (result && result.length > 0) {
        return result.map(item => {
          //判断是否标记了带有子节点
          if (item[this.hasChildrenField] == '1') {
            let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      }
    },
    handleExpand(expanded, record) {
      // 判断是否是展开状态
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        if (record.children.length > 0 && record.children[0].isLoading === true) {
          let params = this.getQueryParams() //查询条件
          params[this.pidField] = record.id
          getAction(this.url.childList, params).then(res => {
            if (res.success) {
              if (res.result && res.result.length > 0) {
                record.children = this.getDataByResult(res.result)
                record.children = record.children.sort(function (a, b) {
                  return b.sorted < a.sorted ? 1 : -1
                })
                this.listArray.push(record.children)
                this.sortMap = new Map()
                for (const i of record.children) {
                  this.sortMap.set(i.sorted, i)
                }
                this.maxNumber = record.children.length
                this.sord = this.popObj(record.children)
                this.dataSource = [...this.dataSource]
              } else {
                record.children = ''
                record.hasChildrenField = '0'
              }
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      } else {
        let keyIndex = this.expandedRowKeys.indexOf(record.id)
        if (keyIndex >= 0) {
          this.expandedRowKeys.splice(keyIndex, 1)
        }
      }
    },
    initDictConfig() {
      //初始化字典 - 来源，多个字典多次获取
      initDictOptions('goods_tag_source_type').then(res => {
        if (res.success) {
          this.dictOptions = res.result
        }
      })
    },
    modalFormOk(formData, arr) {
      console.log(formData)
      if (!formData.id) {
        this.addOk(formData, arr)
      } else {
        this.editOk(formData, this.dataSource)
        this.dataSource = [...this.dataSource]
      }
    },
    editOk(formData, arr) {
      if (arr && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].id == formData.id) {
            arr[i] = formData
            this.sord = this.popObj(arr)
            break
          } else {
            this.editOk(formData, arr[i].children)
          }
          arr = arr.sort(function (a, b) {
            return b.sorted < a.sorted ? 1 : -1
          })
        }
      }
    },
    async addOk(formData, arr) {
      if (arr.length < 1) {
        this.loadData()
      } else {
        this.expandedRowKeys = []
        for (let i of arr) {
          await this.expandTreeNode(i)
        }
      }
    },
    expandTreeNode(nodeId) {
      return new Promise((resolve, reject) => {
        this.getFormDataById(nodeId, this.dataSource)
        let row = this.parentFormData
        this.expandedRowKeys.push(nodeId)
        let params = this.getQueryParams() //查询条件
        params[this.pidField] = nodeId
        getAction(this.url.childList, params).then(res => {
          if (res.success) {
            if (res.result && res.result.length > 0) {
              row.children = this.getDataByResult(res.result)
              this.dataSource = [...this.dataSource]
              resolve()
            } else {
              row.children = ''
              row.hasChildrenField = '0'
              reject()
            }
          } else {
            reject()
          }
        })
      })
    },
    getFormDataById(id, arr) {
      if (arr && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].id == id) {
            this.parentFormData = arr[i]
          } else {
            this.getFormDataById(id, arr[i].children)
          }
        }
      }
    },

    //排序
    sortSub(record) {
      // this.fetchChildList(record)
      console.log(record, 'record')
      if (record.pid == this.parentId) {
        this.maxNumber = this.dataSource.length
      }
      // else {
      //   console.log(this.listArray, 'this.listArray')
      //   this.maxNumber = this.listArray.find(item => {
      //     console.log(item.id)
      //     console.log(record.id)
      //     return item.id === record.pid
      //   }).children.length
      // }

      // return
      this.sorted = record.sorted
      this.record = record
      this.copyHasChild = record.hasChild
      this.copyPid = record.pid
      this.id = record.id
      this.titleName = `调整分类${record.name}的展示顺序`

      this.visible = true
    },
    // 新增
    handleAdd() {
      if (this.dataSource && this.dataSource.length) {
        this.sord = this.popObj(this.dataSource)
      } else {
        this.sord = 1
      }

      let pid = this.parentId
      let type = 'add'
      this.$refs.modalForm.add(pid, this.sord, type)
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    handleEdit(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    async handleAddSub(record) {
      await this.addSub(record)
      this.subExpandedKeys = []
      this.getExpandKeysByPid(record.id, this.dataSource, this.dataSource)
      this.$refs.modalForm.subExpandedKeys = this.subExpandedKeys
      this.$refs.modalForm.title = '添加子分类'
      let type = 'add'
      this.$refs.modalForm.edit({ pid: record.id }, this.sord, type)
      this.$refs.modalForm.disableSubmit = false
    },
    async addSub(record) {
      let params = {
        pid: record.id
      }
      await getAction(this.url.childList, params).then(res => {
        if (res.success) {
          if (res.result && res.result.length > 0) {
            res.result = res.result.sort(function (a, b) {
              return b.sorted < a.sorted ? 1 : -1
            })
            this.getDataByResult(res.result)
            this.sord = this.popObj(res.result)
          } else {
            this.sord = 1
          }
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    popObj(list) {
      let arr = list[list.length - 1]
      let sorted = arr.sorted + 1
      return sorted
    },

    handleDelete: function (record) {
      let that = this
      deleteAction(that.url.delete, { id: record.id }).then(res => {
        if (res.success) {
          //update--begin--autor:lvdandan-----date:20201204------for：JT-31 删除成功后默认展开已展开信息
          that.loadData()
          //update--end--autor:lvdandan-----date:20201204------for：JT-31 删除成功后默认展开已展开信息
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    // 添加子分类时获取所有父级id
    getExpandKeysByPid(pid, arr, all) {
      if (pid && arr && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].id == pid) {
            this.subExpandedKeys.push(arr[i].id)
            this.getExpandKeysByPid(arr[i]['pid'], all, all)
          } else {
            this.getExpandKeysByPid(pid, arr[i].children, all)
          }
        }
      }
    },
    // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
    loadDataByExpandedRows(dataList) {
      console.log(dataList)
      if (this.expandedRowKeys.length > 0) {
        return getAction(this.url.getChildListBatch, { parentIds: this.expandedRowKeys.join(',') }).then(res => {
          if (res.success && res.result.records.length > 0) {
            console.log(res.result.records, 'res.result.records')
            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map()
            for (let item of records) {
              let pid = item[this.pidField]
              if (this.expandedRowKeys.join(',').includes(pid)) {
                let mapList = listMap.get(pid)
                if (mapList == null) {
                  mapList = []
                }
                mapList.push(item)
                listMap.set(pid, mapList)
              }
            }
            let childrenMap = listMap
            let fn = list => {
              if (list) {
                list.forEach(data => {
                  if (this.expandedRowKeys.includes(data.id)) {
                    data.children = this.getDataByResult(childrenMap.get(data.id))

                    fn(data.children)
                  }
                })
              }
            }
            fn(dataList)
          }
        })
      } else {
        return Promise.resolve()
      }
    },
    // 第一次获取二级节点
    async loadDataBySecond(id) {
      return getAction(this.url.getChildListBatch, { parentIds: id }).then(res => {
        if (res.success) {
          let result = res.result
          if (Number(result.total) > 0) {
            this.ipagination.total = Number(result.total)
            const data = this.getDataByResult(res.result.records)
            let dataSource = data.map(item => {
              const isRoot = true
              return { ...item, isRoot }
            })
            let dataInfo = dataSource.filter(item => item.code == this.code)
            this.fetchChildList(dataInfo[0])
          } else {
            this.ipagination.total = 0
            this.dataSource = []
          }
        }
      })
    },
    handlePerssion(record) {
      let params = {
        id: record.id
      }
      queryItemCateById(params).then(res => {
        if (res.code == 0) {
          this.$refs.modalCategory.show(record, res.result)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    fetchChildList(record) {
      console.log(record, 'record')
      // return
      let params = {
        pid: record.id
      }
      getAction(this.url.childList, params).then(res => {
        if (res.success) {
          if (res.result && res.result.length > 0) {
            let arr = res.result.filter(item => item.hasChild == null)
            if (arr.length == res.result.length) {
              this.SecondToLast = true
            }
            this.dataSource = res.result.sort(function (a, b) {
              return b.sorted < a.sorted ? 1 : -1
            })

            this.sortMap = new Map()
            for (const i of this.dataSource) {
              this.sortMap.set(i.sorted, i)
            }
            this.maxNumber = this.dataSource.length

            this.getDataByResult(res.result)
            return this.loadDataByExpandedRows(this.dataSource)
          } else {
          }
        } else {
          this.$message.warning(res.message)
        }
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
